package com.example.healkepdoctor.View.patientInfo.helper;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.example.healkepdoctor.model.Weight;
import com.example.healkepdoctor.util.HttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class patientInfoHelper {
    public static int SUCCESS =1;
    public static int FAILED = 2;
    public static int CONNECT_FAILED = 3;
    private Handler handler;
    public patientInfoHelper(Handler handler){
        this.handler = handler;
    }
    /**
     * 同步
     * @param username
     * @return
     */
    public void getWeight(String username){
        new Thread(()->{
            Map<String,String> map = new HashMap<>();
            map.put("username", username);
            Gson gson = new Gson();
            MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
            RequestBody requestBody = RequestBody.create(gson.toJson(map),mediaType);
            try {
                Response response = HttpUtil.post("/weight/getRecentWeight",requestBody);
                String str = response.body().string();
                if(response.code() != 200){
                    handler.sendEmptyMessage(CONNECT_FAILED);
                    return;
                }
                if(str.length()>3){
                    Weight weight = gson.fromJson(str,Weight.class);
                    Message msg = new Message();
                    msg.what = SUCCESS;
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("weight",weight);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                }else{
                    handler.sendEmptyMessage(FAILED);
                }

            } catch (IOException e) {
                handler.sendEmptyMessage(CONNECT_FAILED);
                e.printStackTrace();
            }
        }).start();
    }
}
